import csv
import json
import time

from django.db.models import Sum
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

from la import models
from la.view.func import ishavesku, ishaveskuandnum


def RKinfo(req):
    """入库单列表"""
    rkinfos = models.RKinfo.objects.all()
    return render(req, "RK_info.html", {"rkinfo": rkinfos})


def RKinfo_add(req):
    """新增入库单"""
    """还没有SKU验证"""
    if req.method == "GET":
        info = req.session["info"]
        strore_id = info['storecode']

        if strore_id == 1:
            storeinfos = models.storeinfo.objects.filter(id__gt = 1).all()
            print(storeinfos)
        else:
            storeinfos = models.storeinfo.objects.filter(id = strore_id).all()
        ##print(info['storecode'])

        return render(req, "RK_info_add.html", {"storeinfo": storeinfos})
    if req.method == "POST":
        fh = req.POST.get('fh')
        sh = req.POST.get('sh')
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        lis = req.POST.get('data')
        re = json.loads(lis)
        s = ishavesku(re)
        if s:
            fhinfo = models.RKinfo(rkName = fh, store_id = sh, rkData = dt, bz = "无备注")
            fhinfo.save()
            id = fhinfo.id
            for item in re:
                if item['款号'] != '款号':
                    fhinfos = models.RKinfoList(rkinfo_id = id, sku = item['款号'], num = item['数量'], cost = item['成本'])
                    fhinfos.save()
                    num = models.inventory.objects.filter(sku = item['款号'],
                                                          storecode_id = sh).first()

                    if num == None:
                        aa = models.inventory(sku = item['款号'], num = item['数量'], storecode_id = sh, shnum = 0,
                                              fhnum = 0)
                        aa.save()
                    else:
                        a = models.inventory.objects.filter(sku = item['款号'], storecode_id = sh).update(
                            num = int(num.num) + int(item['数量']))
            re = {"re": "操作成功"}
        else:
            re = {"re": "操作失败"}
        return JsonResponse(re)


def rkinfo_edit(req, nid):
    """入库信息修改操作"""
    if req.method == "GET":
        fhlist = models.RKinfoList.objects.filter(rkinfo_id = nid).all()
        fhinfo = models.RKinfo.objects.filter(id = nid).all().first()
        return render(req, "RK_info_edit.html", {"fhlist": fhlist, "fhinfo": fhinfo})


def CKinfo(req):
    """出库单列表"""
    ckinfos = models.CKinfo.objects.all()
    return render(req, "CK_info.html", {"ckinfo": ckinfos})


def CKinfo_add(req):
    """新增出库单"""
    if req.method == "GET":
        info = req.session["info"]
        strore_id = info['storecode']
        if strore_id == 1:
            storeinfos = models.storeinfo.objects.filter(id__gt = 1).all()
        else:
            storeinfos = models.storeinfo.objects.filter(id = strore_id).all()
        return render(req, "CK_info_add.html", {"storeinfo": storeinfos})
    if req.method == "POST":
        fh = req.POST.get('fh')
        sh = req.POST.get('sh')
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        list = req.POST.get('data')
        re = json.loads(list)
        s = ishaveskuandnum(re, fh)
        if s:
            ckinfo = models.CKinfo(ckName = sh, store_id = fh, ckData = dt, bz = "无备注")
            ckinfo.save()
            id = ckinfo.id
            for item in re:
                if item['款号'] != '款号':
                    ckinfos = models.CKinfoList(ckinfo_id = id, sku = item['款号'], num = item['数量'])
                    ckinfos.save()
                    num = models.inventory.objects.filter(sku = item['款号'], num__gte = item['数量'],
                                                          storecode_id = fh).first().num
                    a = models.inventory.objects.filter(sku = item['款号'], num__gte = item['数量'],
                                                        storecode_id = fh).update(num = int(num) - int(item['数量']))
            re = {"re": "提交成功"}

        else:
            re = {"re": "操作失败，款号不存在"}
        return JsonResponse(re)


def ckinfo_edit(req, nid):
    """出库信息修改操作"""
    if req.method == "GET":
        fhlist = models.CKinfoList.objects.filter(ckinfo_id = nid).all()
        fhinfo = models.CKinfo.objects.filter(id = nid).all().first()
        return render(req, "CK_info_edit.html", {"fhlist": fhlist, "fhinfo": fhinfo})


def DBinfo(req):
    """调拨单列表"""
    dbinfos = models.DBinfo.objects.all()
    return render(req, "DB_info.html", {"dbinfo": dbinfos})


def DBinfo_add(req):
    """调拨出库单"""
    if req.method == "GET":
        storeinfos = models.storeinfo.objects.filter(id__gt = 1).all()
        return render(req, "DB_info_add.html", {"storeinfo": storeinfos})
    # print(req.POST)
    fh = req.POST.get('fh')
    sh = req.POST.get('sh')
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    list = req.POST.get('data')
    re = json.loads(list)
    s = ishaveskuandnum(re, fh)
    if s:
        DBinfo = models.DBinfo(ckStore_id = fh, rkStore_id = sh, ckData = dt, state = 0, bz = "无备注")
        DBinfo.save()
        id = DBinfo.id
        for item in re:
            if item['款号'] != '款号':
                DBinfos = models.DBinfoList(dbinfo_id = id, sku = item['款号'], num = item['数量'])
                DBinfos.save()
                num = models.inventory.objects.filter(sku = item['款号'], num__gte = item['数量'],
                                                      storecode_id = fh).first()
                a = models.inventory.objects.filter(sku = item['款号'], num__gte = item['数量'], storecode_id = fh).update(
                    num = int(num.num) - int(item['数量']), fhnum = int(num.fhnum) + int(item['数量']))
                '''出库完成--对方库入库'''
                num = models.inventory.objects.filter(sku = item['款号'],
                                                      storecode_id = sh).first()
                if num == None:
                    aa = models.inventory(sku = item['款号'], num = 0, storecode_id = sh, shnum = item['数量'], fhnum = 0)
                    aa.save()
                else:
                    a = models.inventory.objects.filter(sku = item['款号'], storecode_id = sh).update(
                        shnum = int(num.shnum) + int(item['数量']))

        re = {"re": "提交成功"}

    else:
        re = {"re": "操作失败，款号不存在"}
    return JsonResponse(re)


def DBinfo_edit(req, nid):
    """入库信息修改操作"""
    if req.method == "GET":
        fhlist = models.DBinfoList.objects.filter(dbinfo_id = nid).all()
        fhinfo = models.DBinfo.objects.filter(id = nid).all().first()
        return render(req, "DB_info_edit.html", {"fhlist": fhlist, "fhinfo": fhinfo})


def DBinfo_confirm(req):
    '''还差修改调拨单状态'''
    fh = req.POST.get('fh')
    fh = models.storeinfo.objects.filter(name = fh).first().id
    sh = req.POST.get('sh')
    sh = models.storeinfo.objects.filter(name = sh).first().id
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    list = req.POST.get('data')
    re = json.loads(list)
    for item in re:
        if item['款号'] != '款号':
            num = models.inventory.objects.filter(sku = item['款号'], num__gte = item['数量'],
                                                  storecode_id = fh).first()
            models.inventory.objects.filter(sku = item['款号'], num__gte = item['数量'], storecode_id = fh).update(
                fhnum = int(num.fhnum) - int(item['数量']))
            '''出库完成--对方库入库'''
            num = models.inventory.objects.filter(sku = item['款号'],
                                                  storecode_id = sh).first()
            models.inventory.objects.filter(sku = item['款号'], storecode_id = sh).update(
                shnum = int(num.shnum) - int(item['数量']))

    re = {"re": "提交成功"}

    return JsonResponse(re)


def PDinfo(req):
    """盘点单列表"""
    if req.method == "GET":
        pdlist = models.PDinfo.objects.all()

        return render(req, "PD_info.html", {"pdlist": pdlist})


def PDinfo_add(req):
    info = req.session.get("info")
    if req.method == "GET":
        try:
            pdid = models.PDinfo.objects.last().id
        except Exception as e:
            pdid = 1
        else:
            pdid = int(pdid) + 1
        inre = models.inventory.objects.filter(storecode_id = info['storecode'], num__gt = 0)
        return render(req, "PD_info_add.html", {"re": inre, "info": info, "pdid": pdid})
    if req.method == "POST":
        lis = req.POST.get('data')
        lis = json.loads(lis)
        a = models.PDinfo.objects.create(pdStore_id = info['storecode'], state = 0, bz = "")
        for item in lis:
            if item['款号'] != '款号':
                models.PDinfoList.objects.create(sku = item["款号"], num = item["实际数量"], pdnum = item["盘点数量"],
                                                 cynum = item["差异数量"], pdInfoID_id = a.id)
        re = {"re": "提交成功"}
        return JsonResponse(re)


def PDinfo_edit(req, nid):
    info = req.session.get("info")
    if req.method == "GET":
        inre = models.PDinfoList.objects.filter(pdInfoID_id = nid).all()
        return render(req, "PD_info_edit.html", {"re": inre, "info": info, "pdid": nid})
    if req.method == "POST":
        lis = req.POST.get('data')
        lis = json.loads(lis)
        print(info)
        for item in lis:
            if item['款号'] != '款号':
                models.PDinfoList.objects.filter(sku = item["款号"], pdInfoID_id = nid).update(num = item["实际数量"],
                                                                                             pdnum = item["盘点数量"],
                                                                                             cynum = item["差异数量"])
        re = {"re": "提交成功"}
        return JsonResponse(re)


def KCinfo(req):
    """库存单列表"""
    if req.method == "GET":
        info = req.session.get("info")
        inre = models.inventory.objects.filter(storecode_id = info['storecode'])
        nums = models.inventory.objects.filter(storecode_id = info['storecode']).aggregate(num = Sum("num"))
        return render(req, "KC_info.html", {"re": inre, "nums": nums})


def packageKCinfo(req):
    """套餐库存单列表"""
    if req.method == "GET":
        info = req.session.get("info")
        inre = models.packageInventoryList.objects.filter(storecode_id = info['storecode'])
        return render(req, "packageKC_info.html", {"re": inre})


def sample(req):
    info = req.session.get("info")
    storeid = info['storecode']
    samplelist = models.sample.objects.filter(store_id = storeid).all()
    return render(req, "sample_info.html", {"sample": samplelist})


def sample_add(req):
    re = {"re": "提交失败"}
    if req.method == "GET":
        return render(req, 'simple_add.html')
    if req.method == "POST":
        lis = req.POST.get('data')
        re = json.loads(lis)
        info = req.session.get("info")
        storeid = info['storecode']
        s = ishaveskuandnum(re, storeid)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if s:
            for item in re:
                if item["数量"] != "数量":
                    sample = models.sample.objects.create(sku = item['款号'], num = item['数量'], time = dt,
                                                          store_id = storeid)
                    num = models.inventory.objects.filter(storecode = storeid, sku = item['款号']).first().num
                    re = models.inventory.objects.filter(storecode = storeid, sku = item['款号']).update(
                        num = int(num) - int(item['数量']))
                    re = {"re": "提交成功"}
        else:
            re = {"re": "提交失败"}

    return JsonResponse(re)


def inventoryList(req):
    info = req.session.get("info")
    response = HttpResponse(content_type = 'text/csv')
    response['Content-Disposition'] = 'attachment; filename="inventory.csv"'
    writer = csv.writer(response)
    writer.writerow(['款号', '数量', '已发货数量', '未收货数量'])
    list_info = models.inventory.objects.filter(storecode_id = info['storecode']).all().values_list('sku', 'num',
                                                                                                    'fhnum', 'shnum')
    for li in list_info:
        writer.writerow(li)
    return response
